import React, { useReducer,useContext } from 'react'

const conText = React.createContext()

export default function App() {
    const intialState={
        a:"海绵宝宝",
        b:"派大星"
    }
    const reducer=(prevState,action)=>{
        let newState={...prevState}
        switch(action.type){
            case "child2":
                newState.a=action.value
                return newState
            case "child3":
                newState.b=action.value
                return newState
            default:
                return prevState
        }
    }
    // state:状态值，dispatch是方法，useReducer的两个参数：reducer是方法名，intialState是初始状态对象
    const [state,dispatch]=useReducer(reducer,intialState)
    return (
        <conText.Provider value={{
            state,dispatch
        }}>
            <div>
                <Child1 />
                <Child2 />
                <Child3 />
            </div>
        </conText.Provider>

    )
}
function Child1() {
    const {dispatch}=useContext(conText)
    return (
        <div>
            <button onClick={()=>{
                dispatch({
                    type:"child2",
                    value:"蜡笔小新"
                })
            }}>Child1-改变Child2</button>
            <button onClick={()=>{
                dispatch({
                    type:"child3",
                    value:"干物妹小埋"
                })
            }}>Child1-改变Child3</button>
        </div>
    )
}
function Child2() {
    const {state}=useContext(conText)
    return (
        <div>Child2-{state.a}</div>
    )
}
function Child3() {
    const {state}=useContext(conText)
    return (
        <div>Child3--{state.b}</div>
    )
}
